package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper  logininfoMapper;
    @Override
    @Transactional
    public void patchDel(List<Long> ids) {
        employeeMapper.patchDel(ids);
    }

    /**
     * 需要及联操作登录信息表
     * @param employee
     */
    @Override
    public void add(Employee employee) {
        initEmployee(employee);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }

    private void initEmployee(Employee employee) {
        //生成随机32位的salt
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

    @Override
    public void update(Employee employee) {
        super.update(employee);
    }

    @Override
    @Transactional
    public void remove(Long id) {
        // 通过员工id查询员工 从而获取到loginInfoId
        Employee employee = employeeMapper.loadById(id);
        if(employee != null){
            // 删除loginInfo
            // 删除employee
            logininfoMapper.delete(employee.getLogininfo_id());
            employeeMapper.delete(id);
        }

    }
}
